package com.gxuwz.medical.web.servlet.role;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gxuwz.medical.dao.RoleDao;
import com.gxuwz.medical.database.DbUtil;
import com.gxuwz.medical.domain.role.Role;
import com.gxuwz.medical.tools.ResponseUtil;

import net.sf.json.JSONObject;

public class DoSaveRoleAccreditServlet extends HttpServlet {
	DbUtil dbUtil = new DbUtil();
	RoleDao roleDao = new RoleDao(); // 用户数据操作类

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		SaveRoleAccredit(request, response);
	}

	private void SaveRoleAccredit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("来到了角色授权");
		request.setCharacterEncoding("utf-8");
		String id = request.getParameter("id");
		int ids = Integer.valueOf(id).intValue();
//		System.out.println(";ids==" + ids);
		Role role = new Role(ids);
		RoleDao roleDao = new RoleDao();
		List<Role> list = roleDao.findById(role);
//		System.out.println("list.get(1)=" + list.get(0).getRoleid());
		String RoleId = list.get(0).getRoleid();

		/**
		 * 接受从前端传递过来的json数据,要注意引入解析json的包
		 */

		// System.out.println(";id==" + id);
		String name = request.getParameter("params");
//		System.out.println("name=" + name);
		String[] sourceStrArray = name.split(",");
		// System.out.println("sourceStrArray==" + sourceStrArray);
		for (int i = 0; i < sourceStrArray.length; i++) {
			String menuid = sourceStrArray[i];
			// System.out.println("RoleId=" + RoleId + "menuid=" + menuid);
			JSONObject result = new JSONObject();
			try {
				roleDao.SaveRoleAccredit(RoleId, menuid);
				result.put("success", "true");
				System.out.println("角色授权成功!!!");
				ResponseUtil.write(response, result);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

}